﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class BundleEditor : System.Web.UI.UserControl
{
    /// <summary>
    /// Gets or sets the ID of the application for which this BundleEditor shows resource bundles.
    /// </summary>
    /// <value>The application ID.</value>
    public string ApplicationID {
        get { return dsMain.SelectParameters[0].DefaultValue; }
        set { dsMain.SelectParameters[0].DefaultValue = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            BindItemGrid();
        }
        /*bool hasRows = false;
        foreach(GridViewRow row in grdBundles.Rows) {
            if(row.RowType == DataControlRowType.DataRow) {
                hasRows = true;
                break;
            }
        }
        pnlNoBundles.Visible = !hasRows;*/
        lblError.Visible = false;
    }

    /// <summary>
    /// Handles the add and edit commands event of the grdBundles control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCommandEventArgs"/> instance containing the event data.</param>
    protected void grdBundles_RowCommand(object sender, GridViewCommandEventArgs e) {
        string cmd = e.CommandName.ToLower();
        switch(cmd) {
            case "addnew":
                Page.Validate("newitem");
                if(!Page.IsValid) {
                    return;
                }
                ObjectDataSourceView view = new ObjectDataSourceView(dsMain, "bundles", HttpContext.Current);
                view.InsertMethod = "AddBundle";
                view.DataObjectTypeName = "RBBundle";
                view.TypeName = dsMain.TypeName.ToString();
                string bundleName = (grdBundles.FooterRow.FindControl("txtName") as TextBox).Text;
                Dictionary<string, object> dict = new Dictionary<string, object>() {
                    { "Name", bundleName },
                    { "ApplicationID", ApplicationID },
                };
                try {
                    view.Insert(dict);
                } catch(Exception ex) {
                    lblError.Text = string.Format(Resources.Errors.Error + ": " + ex.InnerException == null ? ex.Message : ex.InnerException.Message);
                    lblError.Visible = true;
                }
                BindItemGrid();
                break;
            case "update":
                GridViewRow row = (e.CommandSource as WebControl).NamingContainer as GridViewRow;
                Page.Validate("edititem");
                if(!Page.IsValid) {
                    return;
                }
                break;
        }
    }

    /// <summary>
    /// Checks for exceptions thrown by the datasource when updating.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdatedEventArgs"/> instance containing the event data.</param>
    protected void grdBundles_RowUpdated(object sender, GridViewUpdatedEventArgs e) {
        if(e.Exception != null) {
            Label lblError = grdBundles.Rows[grdBundles.EditIndex].FindControl("lblError") as Label;
            if(lblError != null) {
                lblError.Text = e.Exception.InnerException == null ? e.Exception.Message : e.Exception.InnerException.Message;
                lblError.Visible = true;
                e.KeepInEditMode = true;
                e.ExceptionHandled = true;
            }
        }
    }

    /// <summary>
    /// Checks the length is less than 255 characters.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
    protected void vldNameLength_ServerValidate(object sender, ServerValidateEventArgs e) {
        e.IsValid = e.Value.Length <= 255;
    }

    /// <summary>
    /// Adds an empty footer row if no rows exists.
    /// </summary>
    /// <param name="data">The data.</param>
    /// <returns></returns>
    protected System.Collections.IEnumerable grdItemList_MustAddARow(System.Collections.IEnumerable data) {
        return new List<RBBundle>() {
            new RBBundle()
        };
    }

    /// <summary>
    /// Shows a prompt to confirm deletion of a row.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnDelete_Click(object sender, EventArgs e) {
        MultiView mltDelete = (sender as Control).FindControl("mltDelete") as MultiView;
        mltDelete.ActiveViewIndex = 1;
    }

    /// <summary>
    /// Binds the GridView and removes gridlines if necessary.
    /// </summary>
    private void BindItemGrid() {
        grdBundles.DataBind();
        if(grdBundles.Rows.Count == 0) {
            grdBundles.GridLines = GridLines.None;
        } else {
            grdBundles.GridLines = GridLines.Both;
        }
    }
}
